/**  
 * 
 * @Title:  AbstarctPoolClientManager.java   
 * @Package com.org.framework.net.tcp   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: 123774135@qq.com     
 * @date:   2018年7月5日 下午6:16:35   
 * @version V1.0 
 * @Copyright: 2018 www.tydic.com Inc. All rights reserved. 
 * 
 */  
package com.bicon.base.data.common.net.tcp;

import java.net.InetSocketAddress;

import com.bicon.base.data.common.net.pool.AbstarctDefaultChannelPoolHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.FixedChannelPool;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;

/**   
 * @ClassName:  AbstarctPoolClientManager   
 * @Description:采用客户端连接池进行管理  
 * @author: 123774135@qq.com 
 * @date:   2018年7月5日 下午6:16:35   
 *     
 * @Copyright: 2018 
 * 
 */
public abstract class AbstractClientPoolManager {

	private Bootstrap bootstrap  = null;
	private NioEventLoopGroup group = new NioEventLoopGroup();
	
	private int port;
	
	private String host;
	
	private FixedChannelPool fixedChannelPool  = null;
	
	
	
	public AbstractClientPoolManager(int port,String host) {
		this.port = port;
		this.host = host;
		
		
	}
	
	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}
	
	public void builder() {
		bootstrap  = new Bootstrap();;
		bootstrap.group(group);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
		fixedChannelPool = new FixedChannelPool (bootstrap.remoteAddress(InetSocketAddress.createUnresolved(this.host, this.port)),buliderChannelPoolHandler(),10);
		
	}

	public abstract AbstarctDefaultChannelPoolHandler buliderChannelPoolHandler();
	
	public void connection(String str) {
			 Future<Channel> f = fixedChannelPool.acquire();
	         f.addListener(new FutureListener<Channel>() {
	             

				@Override
				public void operationComplete(Future<Channel> future) throws Exception {
					if (future.isSuccess()) {
		                 Channel ch = future.getNow();
		                 ch.writeAndFlush(str);
		                 // Release back to pool
		                 fixedChannelPool.release(ch);
		             }
					
				}
	         });
	         //group.shutdownGracefully();
		
	}
	
	
	
}
